"""
https://www.cnblogs.com/long5683/p/9692845.html

"""
import cv2 as cv
import numpy as np
import os
import sys
import matplotlib.pyplot as plt
import datetime
from python_ai.common.xcommon import *

np.random.seed(1)
np.set_printoptions(edgeitems=1000)


spr = 3
spc = 5
spn = 0
plt.figure(figsize=[14, 7])


def my_show_img(img, title="no title", trans=None, **kwargs):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    if trans is not None:
        img = trans(img)
    plt.imshow(img, **kwargs)
    plt.axis('off')
    plt.title(title)


sep('Load')
dir = '../../../../../large_data/pic/watershed/'
name = 'poker_cards.png'
# dir = '../../../../../large_data/pic/'
# name = 'dog_bird.png'
path = os.path.join(dir, name)
src = cv.imread(path, cv.IMREAD_COLOR)
src_ = src.copy()

cv.imshow('1 input', src)

sep('255x3=>0')
src[src[:, :] == (255, 255, 255)] = 0
cv.imshow('2 src 255x3=>0', src)
print_numpy_ndarray_info(src, 'src')

sep('lap')
lap = cv.Laplacian(src, cv.CV_32F, None, 3)
print_numpy_ndarray_info(lap, 'lap')
cv.normalize(lap, lap, 0, 255, cv.NORM_MINMAX)
lap = np.uint8(lap)
print_numpy_ndarray_info(lap, 'lap')
cv.imshow('2.1 lap', lap)

sep('sub')
sub = cv.subtract(src, lap)
cv.imshow('2.2 sub', sub)

sep('gray')
gray = cv.cvtColor(sub, cv.COLOR_BGR2GRAY)
cv.imshow('3 gray', gray)

sep('bin')
ret, bin = cv.threshold(gray, 0, 255, cv.THRESH_OTSU + cv.THRESH_BINARY)
print_numpy_ndarray_info(bin, 'bin')
cv.imshow('4 bin', bin)

sep('dist')
dist = cv.distanceTransform(bin, cv.DIST_L2, 3)
print_numpy_ndarray_info(dist, 'dist')
cv.normalize(dist, dist, 0, 1, cv.NORM_MINMAX)  # ATTENTION: Normalization after distanceTransform is important.
print_numpy_ndarray_info(dist, 'dist')
cv.imshow('5 dist', dist)

sep('threshold')
ret, thresh = cv.threshold(dist, 0.4, 1, cv.THRESH_BINARY)
thresh *= 255.
thresh = np.uint8(thresh)
cv.imshow('6 thresh', thresh)

sep('contours')
contours, _ = cv.findContours(thresh, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
len_con = len(contours)

sep('color table')
colorTab = [(255, 255, 255)]
for i in range(len_con * 2):
    b = np.random.randint(0, 256)
    g = np.random.randint(0, 256)
    r = np.random.randint(0, 256)
    colorTab.append((b, g, r))
colorTab = np.uint8(colorTab)

sep('connected')
ret, conn = cv.connectedComponents(thresh)
conn_show = colorTab[conn]
cv.imshow('7 conn_show', conn_show)

sep('watershed')
src = src_.copy()
markers = cv.watershed(src, conn)
markers[markers == -1] = 0
markers_show = colorTab[markers]
cv.imshow('7 markers_show', markers_show)

sep('split')
src[markers == 0] = (0, 255, 0)
cv.imshow('8 ticked', src)

cv.waitKey()
cv.destroyAllWindows()
